﻿using System;
using System.Linq.Expressions;

namespace MySql.Simple.Mapper.Linq.ExpressionVisitors
{
    /// <summary>
    /// Transforms <see cref="NewExpression"/> objects into MySQL syntax
    /// </summary>
    public class MemberExpressionVisitor : IExpressionVisitor
    {
        /// <summary>
        /// Determines whether this instance can visit the specified expression.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <returns>
        /// 	<c>true</c> if this instance can visit the specified expression; otherwise, <c>false</c>.
        /// </returns>
        public bool CanVisit(Expression expression)
        {
            return expression is MemberExpression;
        }

        /// <summary>
        /// Visits the specified expression and returns a string representation of it's contents.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="query"></param>
        /// <returns></returns>
        public SqlQuery Visit(Expression expression, SqlQuery query)
        {
            var memberExpression = (MemberExpression)expression;

            if (memberExpression.NodeType == ExpressionType.MemberAccess)
            {
                query.Fields += "`" + memberExpression.Member.Name + "`";
            }
            else
            {
                var lambda = Expression.Lambda<Func<object>>(memberExpression.Expression);

                var invoke = lambda.Compile().Invoke();

                foreach (var fieldInfo in invoke.GetType().GetFields())
                {
                    if (fieldInfo.Name != memberExpression.Member.Name) continue;

                    var value = fieldInfo.GetValue(invoke);

                    query.Where += value.ToMySqlSyntax();
                }
            }

            return query;
        }
    }
}
